<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Request;
use app\core\Service;
use app\core\util\Encryp;
use app\core\util\Token;
use app\model\Temple;
use app\model\TempleImage;
use think\facade\Db;

/**
 * @extends Service<TempleService>
 */
class TempleService extends Service
{
    public function login(string $account, string $password)
    {
        $Temple = Temple::where([
            'account' => $account
        ])->find();
        if (!$Temple) {
            throw new BusinessException('帐号不存在');
        }
        if ($Temple['passwords'] !== Encryp::password($password)) {
            throw new BusinessException('密码不正确');
        }
        if ($Temple['status'] != 1) {
            throw new BusinessException('帐号已禁用');
        }

        // 保存最后登录时间
        $Temple->save([
            'login_time' => date('Y-m-d H:i:s', time()),
            'login_ip' => Request::invoke()->ip()
        ]);
        $templeInfo = $Temple->toArray();
        // 生成 Token
        $token = Token::invoke()
            ->setTempleId($templeInfo['temple_id'])
            ->setTempleInfo($templeInfo)
            ->genTempleToken();
        return $token;
    }

    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        $w[] = ['is_delete', '=', 0];
        if (!empty($searchQuery['name']) && $searchQuery['name'] != '') {
            $w[] = ['name', 'like', "%" . $searchQuery['name'] . "%"];
        }
        if (!empty($searchQuery['account']) && $searchQuery['account'] != '') {
            $w[] = ['account', '=', $searchQuery['account']];
        }
        if (!empty($searchQuery['status']) && $searchQuery['status'] != '') {
            $w[] = ['status', '=', $searchQuery['status']];
        }
        if (!empty($searchQuery['timeValues'])) {
            if (!is_array($searchQuery['timeValues'])) {
                $timeValues = json_decode($searchQuery['timeValues']);
            } else {
                $timeValues = $searchQuery['timeValues'];
            }
            $w[] = ['create_time', 'between', $timeValues];
        }
        $map = Temple::where($w)->page($page, $limit);
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    public function save($data, $id = null)
    {
        Db::startTrans();
        try {
            $temple = [];
            if (!empty($data['name']) && $data['name'] != '') {
                $temple['name'] = $data['name'];
            }
            if (!empty($data['address']) && $data['address'] != '') {
                $temple['address'] = $data['address'];
            }
            if (!empty($data['status']) && $data['status'] != '') {
                $temple['status'] = $data['status'];
            }
            if (!empty($data['lng']) && $data['lng'] != '') {
                $temple['lng'] = $data['lng'];
            }
            if (!empty($data['lat']) && $data['lat'] != '') {
                $temple['lat'] = $data['lat'];
            }
            if (!empty($data['account']) && $data['account'] != '') {
                $temple['account'] = $data['account'];
            }
            if (!empty($data['password']) && $data['password'] != '') {
                $temple['password'] = md5($data['password']);
            }
            if (!empty($data['rate']) && $data['rate'] != '') {
                $temple['rate'] = $data['rate'];
            }

            if (empty($id)) {
                if (!empty($data['name']) && $data['name'] != '') {
                    $w = [];
                    $w[] = ['name', '=', $data['name']];
                    $w[] = ['is_delete', '=', 0];
                    $info = Temple::where($w)->find();
                    if ($info) {
                        throw new \Exception('寺庙已存在!');
                    }
                }
                Temple::create($temple);
            } else {
                $info = Temple::where('temple_id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save($temple);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function info($id)
    {
        $info = Temple::where('temple_id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        $imageList = [];
        $templeImageList = (new TempleImage())->where('temple_id', $id)->select()->toArray();
        if (!empty($templeImageList)) {
            $imageList = $templeImageList;
        }
        $info = $info->toArray();
        $info['image_list'] = $imageList;
        return $info;
    }

    public function del($id)
    {
        $info = Temple::where('temple_id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->save(['is_delete' => 1]);
    }

    public function saveTemple($id)
    {
        $root = __DIR__ . "/../../public";
        $info = Temple::where('temple_id', $id)->find();
        if (empty($info)) {
            throw new BusinessException('数据不存在');
        }
        if ($info['image_url'] != '') {
            $filePath = $root . $info['image_url'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        $path = '/storage/' . date('Ymd') . "/" . md5(time()) . '.png';
        $image_url = $root . $path;
        // 确保目录存在
        $directory = dirname($image_url);
        if (!is_dir($directory)) {
            mkdir($directory, 0755, true); // 第三个参数 true 表示可以创建多级目录
        }
        $appid = $this->app->config->get('app.app_id');
        $secret = $this->app->config->get('app.app_secret');
        $tokenAccessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $access_token_json = file_get_contents($tokenAccessUrl);
        $access_token_array = json_decode($access_token_json, true);
        $access_token = $access_token_array['access_token'];
        //生成小程序码的API地址
        $qrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $param = [
            'path' => 'pages/templelist/templedetail?id=' . $id, //小程序的页面路径
            'width' => 300
        ];
        $postData = json_encode($param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $qrcodeUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        $result = curl_exec($ch);
        curl_close($ch);
        file_put_contents($image_url, $result);
        $info->save(['image_url' => $path]);
        return $path;
    }

    public function updateAll()
    {
        $url = 'http://device.api.fjxmlz.com:18081/api/projects';
        $header = [
            'Content-Type: application/json'
        ];
        $params = '';
        $result = $this->request_post($url, $header, $params);
        $result = json_decode($result, true);
        if (!empty($result['data'])) {
            foreach ($result['data'] as $value) {
                $w = [];
                $w[] = ['name', '=', $value['name']];
                $w[] = ['is_delete', '=', 0];
                $info = Temple::where($w)->find();
                if ($info) {
                    continue;
                }
                $data = [
                    'account' => $value['id'],
                    'name' => $value['name'],
                ];
                $this->save($data);
            }
        }
        return true;
    }

    private function request_post($url = '', $header = array(), $data_string = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
        }
        $result = curl_exec($ch);
        return $result;
    }
}